// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
mod app_handle_manager; // 声明模块
mod tray;

use app_handle_manager::AppHandleManager;
use tauri::{Emitter, Manager, Window};
// 引入结构体
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_updater::UpdaterExt;
use tray::try_register_tray_icon;
#[cfg(target_os = "macos")]
use cocoa::appkit::{NSColor, NSWindow};
#[cfg(target_os = "macos")]
use cocoa::base::{id, nil};

#[tauri::command]
fn update_tray_title(title: &str) {
    if let Some(tray) = AppHandleManager::global().get_tray() {
        let title = title.to_string();
        tauri::async_runtime::spawn(async move {
            if let Err(e) = tray.set_title(Some(&title)) {
                eprintln!("设置托盘标题失败: {:?}", e);
            }
        });
    }
}

#[tauri::command]
fn update_app(token: &str, window: Window, force: bool) {
    println!("更新测试开始啦......");
    println!("token是多少：{}", token);
    
    // 向前端发送日志事件
    if let Err(e) = window.emit("rust-log", "更新测试开始啦......") {
        eprintln!("发送日志事件失败: {:?}", e);
    }
    if let Err(e) = window.emit("rust-log", format!("token是多少：{}", token)) {
        eprintln!("发送日志事件失败: {:?}", e);
    }
    
    let token_owned = token.to_string();
    tauri::async_runtime::spawn(async move {
        update(&token_owned, force).await.unwrap();
        if !force {
            if !window.is_enabled().unwrap_or(false) {
                window.set_enabled(true);
                window.set_focus();
            }
        }
    });
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let app = tauri::Builder::default()
        .plugin(tauri_plugin_updater::Builder::new().build())
        .setup(|app| {
            // 托盘
            AppHandleManager::global().init(app.handle().clone());
            try_register_tray_icon(app.handle())?;

            // let window = app.build().unwrap();

            #[cfg(target_os = "macos")]
            unsafe {
                if let Some(window) = app.get_webview_window("main") {

                    let ns_window = window.ns_window().unwrap() as id;
                    let bg_color = NSColor::colorWithRed_green_blue_alpha_(
                        nil,
                        245.0 / 255.0,
                        246.0 / 255.0,
                        247.0 / 255.0,
                        1.0,
                    );
                    ns_window.setBackgroundColor_(bg_color);
                }
            }

            Ok(())
        })
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![update_tray_title, update_app])
        .build(tauri::generate_context!())
        .expect("error while running tauri application");

    app.run(|app_handle, e| match e {
        #[cfg(target_os = "macos")]
        tauri::RunEvent::Reopen {
            has_visible_windows,
            ..
        } => {
            if !has_visible_windows {
                if let Some(window) = AppHandleManager::global()
                    .get_handle()
                    .get_webview_window("main")
                {
                    window.show();
                }
            }
        }
        _ => {}
    });
}

async fn update(_token: &str, force: bool) -> tauri_plugin_updater::Result<()> {
    let app = AppHandleManager::global().get_handle();
    let author =  format!(
        "Bearer {token}",
        token = _token.trim_matches('"').to_string()
    );
    let target = "windows";
    #[cfg(target_os = "macos")]
    let target = "macos";

    println!("开始检查更新，target: {}", target);
    println!("token是多少：{}", _token);
    
    // 向前端发送日志
    if let Some(window) = app.get_webview_window("main") {
        let _ = window.emit("rust-log", format!("开始检查更新，target: {}", target));
        let _ = window.emit("rust-log", "正在构建更新检查器...");
    }
    
    // 移除Authorization头部要求，允许未登录用户也能自动更新
    match app.updater_builder()
        .target(target)
        // .header("Authorization", author)?
        .build() {
        Ok(updater) => {
            if let Some(window) = app.get_webview_window("main") {
                let _ = window.emit("rust-log", "更新检查器构建成功，开始检查版本...");
                let current_version = app.package_info().version.to_string();
                let _ = window.emit("rust-log", format!("请求URL: https://mail-api.lq-assets.com/system/api/versions/check/{}/{}", target, current_version));
            }
            
            match updater.check().await {
                Ok(Some(update)) => {
                    if let Some(window) = app.get_webview_window("main") {
                        let _ = window.emit("rust-log", format!("发现新版本: {}", update.version));
                        let _ = window.emit("rust-log", format!("更新内容: {:?}", update.body));
                    }
                    
                    if let Some(window) = app.get_webview_window("main")  {
                        if !force {
                            // window.set_enabled(false);
                            // 暂时禁用窗口，但不影响对话框显示
                            println!("准备显示更新对话框");
                        }
                    }
                     // 弹出确认对话框
                    let body_display = update.body.as_ref().unwrap_or(&"无更新内容".to_string()).to_owned();
                    let content =  format!(
                        "版本: {version} \r\n 更新内容: {body}",
                        version = update.version,
                        body = body_display
                    );
                    let mut confirmed = true;
                    if !force {
                        println!("显示更新确认对话框");
                        confirmed = app.dialog()
                            .message(content)     
                            .buttons(tauri_plugin_dialog::MessageDialogButtons::YesNo)
                            .title("发现新版本，是否立即更新？")
                            .blocking_show();
                            println!("用户选择: {}", if confirmed { "确认更新" } else { "取消更新" });
                    }

                    // 点击确认 之后下载安装 重启
                    // 根据用户选择处理
                    if confirmed {
                        // 现在才禁用窗口，开始下载
                        if let Some(window) = app.get_webview_window("main") {
                            if !force {
                                window.set_enabled(false);
                            }
                        }

                        let mut downloaded = 0;
                        println!("开始下载更新...");
                        // alternatively we could also call update.download() and update.install() separately
                        update
                        .download_and_install(
                            |chunk_length, content_length| {
                                downloaded += chunk_length;
                                // contentLength = content_length;
                                let size = content_length.unwrap_or(1);
                                let progress = downloaded as u64 * 100 / size;
                                println!("下载进度: {}%", progress);
                                app.emit("update-version-process", progress);
                            },
                            || {
                                println!("download finished");
                            },
                        )
                        .await?;

                        println!("update installed");
                        println!("更新安装完成，准备重启应用");
                        app.restart();
                    } else {
                        // 用户取消更新，重新启用窗口
                        if let Some(window) = app.get_webview_window("main") {
                            window.set_enabled(true);
                            window.set_focus();
                        }
                    }
                },
                Ok(None) => {
                    println!("当前已是最新版本");
                    if let Some(window) = app.get_webview_window("main") {
                        let _ = window.emit("rust-log", "服务器响应: 当前已是最新版本 (返回None)");
                    }
                },
                Err(e) => {
                    println!("更新检查失败: {:?}", e);
                    if let Some(window) = app.get_webview_window("main") {
                        let _ = window.emit("rust-log", format!("更新检查失败: {:?}", e));
                        let _ = window.emit("rust-log", format!("错误详情: {}", e));
                    }
                }
            }
        },
        Err(e) => {
            println!("更新检查器构建失败: {:?}", e);
            if let Some(window) = app.get_webview_window("main") {
                let _ = window.emit("rust-log", format!("更新检查器构建失败: {:?}", e));
            }
        }
    }

    Ok(())
}